package com.apache.member.controller;

import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultMsg;
import com.apache.cache.util.Validator;
import com.apache.database.model.Page;
import com.apache.member.common.ConstantData;
import com.apache.member.common.DateUtil;
import com.apache.member.entity.Member;
import com.apache.member.entity.MemberRole;
import com.apache.member.manager.MemberManager;
import com.apache.member.manager.MemberRoleManager;
import com.apache.member.manager.MemberTypeManager;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.manager.UserManager;

@Controller
@RequestMapping("/admin/member")
public class MemberController {

	@Autowired
	private MemberManager memberManager;

	@Autowired
	private MemberRoleManager memberRoleManager;

	@Autowired
	private MemberTypeManager memberTypeManager;

	@Autowired
	private UserManager userManager;;

	//	@Autowired
	//	private SendEmailPlugin sendEmailPlugin;

	//	@Autowired
	//	private AuditManager auditManager;

	//	@Autowired
	//	private AuditRuleManager auditRuleManager;

	//	@Autowired
	//	private NoticeManager noticeManager;

	//	@Autowired
	//	private PubManager pubManager;

	@RequestMapping("/getMember.action")
	@ResponseBody
	public Map<String, Object> selectById(Member member) {
		ParamsVo<Member> vo = new ParamsVo<Member>();
		vo.setObj(member);
		Map<String, Object> mapData = new HashMap<String, Object>();
		List<Member> list = memberManager.getList(vo);
		if (Validator.isEmpty(list)) {
			return null;
		}
		mapData.put("member", list.get(0));

		return mapData;
	}

	@RequestMapping("/selectById.action")
	@ResponseBody
	public Map<String, Object> selectById(String memberId, HttpServletRequest request, HttpServletResponse response) {

		ParamsVo<Member> vo = new ParamsVo<Member>();

		Map<String, Object> mapData = new HashMap<String, Object>();
		if (Validator.isNotNull(memberId)) {
			ParamsVo<Member> v = new ParamsVo<Member>();
			v.setInfoId(memberId);
			Member member = (Member) memberManager.getInfoById(v);
			mapData.put("rows", member);
		}

		return mapData;
	}

	/**
	 * 添加会员的同时添加user
	 * @param member
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	//@Token(remove = true)
	//防表单重复提交注解
	@RequestMapping("add.action")
	@ResponseBody
	//定义注解
	//${ctx}/admin/member/add.action?memberEname=test123&editType=0
	public ResultMsg add(Member member, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ResultMsg resultMsg = new ResultMsg();
		resultMsg.setFlag(ConstantData.FLAG_FALSE);
		resultMsg.setMsg("操作失败！");
		LoginUser loginUser = PBOSSOTools.getLoginUser(request);
		ParamsVo vo = new ParamsVo();
		//默认注册的是普通会员会员等级1
		String editType = request.getParameter("editType");//TODO
		if ("0".equals(editType)) {//TODO
			member.setAuditStatus(ConstantData.AuditStatus.TEMP);
		} else {
			member.setMemberLevel("2");//TODO
			//	会员编号自动生成		member.setMemberNo(NumberFactory.getNum("1", "XBFAX"));
			member.setAuditStatus(ConstantData.AuditStatus.AUDIT_PASS);
		}
		String now = DateUtil.getNowTime();
		member.setInfoFrom(ConstantData.InfoFrom.OFFLINE);
		member.setStatus(ConstantData.UserStatus.START);
		member.setCreateTime(now);
		member.setCreateUserEname(loginUser.getUserEname());
		member.setRegTime(now);
		String mobile = String.valueOf(Validator.getDefaultStr(member.getMobile(), null));
		if (Validator.isNotNull(mobile)) {
			member.setMobile(mobile);
		}
		vo.setObj(member);
		String memberId = memberManager.saveMemberAndUser(vo);//.saveMemberRoleInfo(vo);
		if (Validator.isNotNull(memberId)) {
			resultMsg.setFlag(ConstantData.FLAG_OK);
			resultMsg.setMsg(memberId);
		} else {
			resultMsg.setFlag(ConstantData.FLAG_FALSE);
			resultMsg.setMsg("账号已存在或网络异常，注册不成功！");
		}
		return resultMsg;
	}

	/**
	 * 查询所有会员列表
	 * @param project
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("queryMemberList.action")
	@ResponseBody
	public Map<String, Object> queryMemberList(Member member, HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows) throws Exception {
		String flag = request.getParameter("flag");
		ParamsVo<Member> vo = new ParamsVo<Member>();
		vo.setObj(member);
		vo.setParams("pageSize", Validator.getDefaultStr(rows, "15"));
		vo.setParams("pageIndex", Validator.getDefaultStr(page, "1"));
		//List<Member> list = memberManager.getList(vo);
		//ActController.setActParams(vo, loginUser);
		Page pageList = memberManager.getPageInfo(vo);
		List<Member> pageObjects = pageList.getPageObjects();

		//给会员增加memberRoles，不考虑事物,此方法会影响效率，应急措施，后续更改。
		for (Member newMember : pageObjects) {
			String memberId = newMember.getMemberId();
			ParamsVo<MemberRole> roleVo = new ParamsVo<MemberRole>();
			MemberRole memberRole = new MemberRole();
			memberRole.setMemberId(memberId);
			roleVo.setObj(memberRole);
			List<MemberRole> memberRoleList = memberRoleManager.getList(roleVo);
			String memberRoles = "";
			if (memberRoleList.size() > 0) {
				for (MemberRole role : memberRoleList) {
					if (Validator.isNull(memberRoles)) {
						memberRoles = role.getRoleEname();
					} else {
						memberRoles = memberRoles + "," + role.getRoleEname();
					}
				}
			}
			newMember.setMemberRoles(memberRoles);
		}

		if (Validator.isNotNull(flag) && "1".equals(flag) && Validator.isNull(member.getMemberEname())) {
			pageObjects = null;
		}
		Map<String, Object> mapData = new HashMap<String, Object>();
		mapData.put("total", pageList.getCount());
		mapData.put("rows", pageObjects);
		return mapData;
		//return list;
	}

	/**
	 * 
	 * description:  member 会员信息预览
	 * @param memberId
	 * @param request
	 * @return  
	 * @author Administrator 
	 * @update 2015-6-25
	 */
	@RequestMapping("memberView.action")
	@ResponseBody
	public Map<String, Object> memberView(String memberId, HttpServletRequest request, HttpServletResponse response) {
		// 查询member基础信息
		ParamsVo<Member> vo = new ParamsVo<Member>();
		vo.setInfoId(memberId);
		Member member = (Member) memberManager.getInfoById(vo);
		Map<String, Object> mapData = new HashMap<String, Object>();
		mapData.put("member", member);
		return mapData;
	}

	/**
	 * 修改会员审核状态和审核意见信息
	 */
	@RequestMapping("editAuditStatus.action")
	@ResponseBody
	public ResultMsg editAuditStatus(String memberId, String auditStatus, String auditMsg, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ResultMsg resultMsg = new ResultMsg();
		resultMsg.setFlag(ConstantData.FLAG_FALSE);
		resultMsg.setMsg("修改失败");
		try {
			LoginUser loginUser = PBOSSOTools.getLoginUser(request);
			if (Validator.isNotNull(memberId)) {
				ParamsVo<Member> bmiVo = new ParamsVo<Member>();
				bmiVo.setInfoId(memberId);
				Member memObj = (Member)memberManager.getInfoById(bmiVo);
				if(memObj!=null){
					memObj.setAuditStatus(auditStatus);
					memObj.setUpdateUserEname(loginUser.getUserEname());
					memObj.setUpdateTime(DateUtil.getNowTime());
					memObj.setStrFiftyEleven(auditMsg);
					bmiVo.setObj(memObj);
					boolean s = memberManager.editInfo(bmiVo);
					if (s) {
						resultMsg.setFlag(ConstantData.FLAG_OK);
						resultMsg.setMsg("操作成功!");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMsg;
	}
	
	/**
	 * 修改会员信息
	 * @param editType 修改类型：1,保存  0,暂存
	 */
	@RequestMapping("edit.action")
	@ResponseBody
	public ResultMsg edit(String editType, String auditType, Member member, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ResultMsg resultMsg = new ResultMsg();
		resultMsg.setFlag(ConstantData.FLAG_FALSE);
		resultMsg.setMsg("修改失败");
		try {
			LoginUser loginUser = PBOSSOTools.getLoginUser(request);
			if (Validator.isNotNull(member.getMemberId())) {
				// 根据保存的类型，判断member状态修改成 0 ： 暂存   91：审核通过
				if (null != editType && "0".equals(editType)) {
					member.setAuditStatus(ConstantData.AuditStatus.TEMP);
				} else if (null != editType && "1".equals(editType)) {
					//					String memberLevel = member.getMemberLevel();
					//					if (Validator.isNotNull(memberLevel)) {
					//						member.setMemberLevel(memberLevel);
					//					} else {
					//						member.setMemberLevel("2");
					//					}
					//					member.setAuditStatus(ConstantData.AuditStatus.AUDIT_PASS);

					//如果审核不通过，再次提交，则将状态修改成为已提交。
					if (ConstantData.AuditStatus.AUDIT_NOPASS.equals(member.getAuditStatus())) {
						member.setAuditStatus(ConstantData.AuditStatus.AUDITING);
					}

				} else {
					member.setAuditStatus(ConstantData.AuditStatus.AUDIT_PASS);
				}
				ParamsVo<Member> bmiVo = new ParamsVo<Member>();
				member.setUpdateTime(DateUtil.getNowTime());
				bmiVo.setObj(member);
				bmiVo.setParams("loginUser", loginUser);
				bmiVo.setParams("flag", "T");
				bmiVo.setParams("userEname", loginUser.getUserEname());
				bmiVo.setParams("pid", loginUser.getUserId());
				bmiVo.setParams("auditType", Validator.getDefaultStr(auditType, null));
				String roleId = request.getParameter("roleId");
				bmiVo.setParams("roleId", roleId);
				String memberRoleId = memberManager.editMemberAndSaveMemberRole(bmiVo);

				if (null != memberRoleId) {
					resultMsg.setFlag(ConstantData.FLAG_OK);
					resultMsg.setMsg("修改成功!");
					String callBack = request.getParameter("callBack");
					if (Validator.isNotNull(callBack)) {
						JSONObject nvo = new JSONObject();
						PrintWriter out = response.getWriter();
						nvo.put("flag", ConstantData.FLAG_OK);
						response.getWriter().write(callBack + "(" + nvo.toString() + ")");
						return null;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMsg;
	}

	/**
	 * 只修改会员信息，和角色无关
	 * @param editType
	 */
	@RequestMapping("editMemberInfo.action")
	@ResponseBody
	public ResultMsg editMemberInfo(Member member, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ResultMsg resultMsg = new ResultMsg();
		resultMsg.setFlag(ConstantData.FLAG_FALSE);
		resultMsg.setMsg("修改失败");
		try {
			LoginUser loginUser = PBOSSOTools.getLoginUser(request);
			if (Validator.isNotNull(member.getMemberId())) {
				ParamsVo<Member> bmiVo = new ParamsVo<Member>();
				member.setUpdateTime(DateUtil.getNowTime());
				member.setUpdateUserEname(loginUser.getUserEname());
				bmiVo.setObj(member);
				boolean res = memberManager.editInfo(bmiVo);
				if (res) {
					resultMsg.setFlag(ConstantData.FLAG_OK);
					resultMsg.setMsg("修改成功");
				}
				String callBack = request.getParameter("callBack");
				if (Validator.isNotNull(callBack)) {
					JSONObject nvo = new JSONObject();
					PrintWriter out = response.getWriter();
					nvo.put("flag", ConstantData.FLAG_OK);
					response.getWriter().write(callBack + "(" + nvo.toString() + ")");
					return null;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMsg;
	}

	/**
	 * 删除会员信息
	 * @param memberId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("delete.action")
	@ResponseBody
	public ResultMsg del(String memberId, HttpServletRequest request, HttpServletResponse response) {
		ResultMsg resultMsg = new ResultMsg();
		resultMsg.setFlag(ConstantData.FLAG_FALSE);
		resultMsg.setMsg("操作失败！");
		ParamsVo<Member> vo = new ParamsVo<Member>();
		if (Validator.isNotNull(memberId)) {

			vo.setInfoId(memberId);

			if (memberManager.deleteMemberAndUser(vo)) {
				resultMsg.setFlag(ConstantData.FLAG_OK);
				resultMsg.setMsg("操作成功！");
			}
		}

		return resultMsg;
	}

	/**
	 * 添加会员（此方法用于先有user后再添加member的场景）
	 * @param member
	 * @param response
	 * @return
	 */
	//@Token(remove = true)
	//防表单重复提交注解
	@RequestMapping("/addMember.action")
	@ResponseBody
	//定义注解
	public ResultMsg addMember(Member member, HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ResultMsg resultMsg = new ResultMsg();
		resultMsg.setFlag(ConstantData.FLAG_FALSE);
		resultMsg.setMsg("操作失败！");
		ParamsVo<Member> vo = new ParamsVo<Member>();
		member.setAuditStatus(ConstantData.AuditStatus.AUDITING);
		member.setInfoFrom(ConstantData.InfoFrom.ONLINE);
		member.setStatus(ConstantData.UserStatus.START);
		String now = DateUtil.getNowTime();
		member.setCreateTime(now);
		member.setCreateUserEname(member.getMemberEname());
		member.setRegTime(now);
		String mobile = String.valueOf(Validator.getDefaultStr(member.getMobile(), null));
		if (Validator.isNotNull(mobile)) {
			member.setMobile(mobile);
		}
		vo.setObj(member);

		LoginUser loginUser = PBOSSOTools.getLoginUser(request);

		vo.setParams("loginUser", loginUser);
		vo.setParams("flag", "T");
		vo.setParams("userEname", loginUser.getUserEname());
		vo.setParams("pid", loginUser.getUserId());
		String memberId = memberManager.saveMemberAndRoles(vo);
		if (Validator.isNotNull(memberId)) {
			resultMsg.setFlag(ConstantData.FLAG_OK);
			resultMsg.setMsg(memberId);
			String callBack = request.getParameter("callBack");
			if (Validator.isNotNull(callBack)) {
				JSONObject nvo = new JSONObject();
				PrintWriter out = response.getWriter();
				nvo.put("flag", ConstantData.FLAG_OK);
				response.getWriter().write(callBack + "(" + nvo.toString() + ")");
				return null;
			}

		} else {
			resultMsg.setFlag(ConstantData.FLAG_FALSE);
			resultMsg.setMsg("会员开通未成功！");
		}

		return resultMsg;
	}

}
